#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>

typedef void (*handler_t)();
std::vector<handler_t> handlers;

void fun_one()
{
  printf("临时任务1\n");
}

void fun_two()
{
  printf("临时任务2\n");
}

void Load()
{
  handlers.push_back(fun_one);
  handlers.push_back(fun_two);
}

void handler()
{
  if(handlers.empty())
    Load();
  for(auto iter : handlers)
    iter();
}

int main()
{
  pid_t pid = fork();
  if(pid == 0)  //child
  {
    printf("child is run, pid is : %d\n", getpid());
    sleep(5);

    //int num = 5;
    //while(num--)
    //{
    //  printf("child is run, pid %d\n", getpid());
    //  sleep(1);
    //}
  }
  else  //parent
  {
    pid_t ret = 0;
    int status = 0;

    do 
    {
      ret = waitpid(-1, &status, WNOHANG);
      if(ret == 0)
      {
        printf("child is running\n");
        handler();
      }
    }while(ret == 0);

      if(ret == pid && WIFEXITED(status))
      {
        printf("wait child 5s success, child return: %d\n", WEXITSTATUS(status));
      }
  
    //while(ret == 0)
    //{  
    //  ret = waitpid(-1, &status, WNOHANG);
    //  //printf("child is running\n");
    //  if(ret == 0)
    //  {
    //    printf("child is running\n");
    //  }

    //  //if(ret == pid && WIFEXITED(status))
    //  //{
    //  //    printf("child success, return: %d\n", WEXITSTATUS(status)); 
    //  //}
    //} 
    //  if(ret == pid && WIFEXITED(status))
    //  {
    //      printf("child success, return: %d\n", WEXITSTATUS(status)); 
    //  }
  }
  return 0;
}



